import Vue from "vue";
import Vuex from "vuex";
import App from "./app.vue";
import createLogger from "./logger/logger.js";
/*elm*/
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-default/index.css';
/*router*/
import VueRouter from 'vue-router'; 
import music from "./components/music.vue"
Vue.use(Vuex);
Vue.use(ElementUI);
Vue.use(VueRouter);



const router = new VueRouter({
  routes: [
    { path: '/detail', component: music },
    { path: '/main', component: App },
    { path: '*', component: App }
  ]
});


const store = new Vuex.Store({
    state: {
        data: {
            filterBox: [],
            listdata: [],
            id : ""
        }
    },
    mutations: {
        ADDFILTER(state, payload){
            state.data.filterBox.push(payload);
        },
        HANDLECLOSE(state, payload){
            state.data.filterBox.splice(state.data.filterBox.indexOf(payload), 1);
        },
        FETCHDATA(state, payload){
            state.data.listdata = payload;
        },
        CHANGEID(state , payload){
            state.data.id = payload;
            router.push({ path: '/detail'});
        },
        GETAll(state, payload) {
            //console.log(state)
            /*payload.forEach(function (item) {
                if (item.id == state.id) {
                    state.data.detail.push(item);
                }
            })*/

        }
    },
    actions: {
        ADDFILTER({dispatch,commit}, payload){
            commit("ADDFILTER",payload);
            dispatch('FETCHDATA')
        },
        HANDLECLOSE({dispatch,commit}, payload){
            commit("HANDLECLOSE",payload);
            dispatch('FETCHDATA')
        },
        FETCHDATA({commit,state}){
            //console.log(state.data.filterBox);
            fetch("/list",{
                "method" : "post" ,
                "headers": {
                    "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
                },
                "body" : "filter=" + encodeURI(JSON.stringify(state.data.filterBox))
            }).then((res)=>{
                res.json().then((data)=>{
                    commit("FETCHDATA",data)
                });
            });
        },
        GETALL({ commit }, payload) {

            $.get("/getall", function (data) {
                commit("GETAll", data)
            })
        }
    },
    getters: {
        getFilter(state){
            return state.data.filterBox;
        }
    },
    strict: process.env.NODE_ENV !== 'production',
    plugins: [createLogger()]

});

new Vue({
    el: "#root",
    store,
    router,
    components: {
        App
    }
});

router.beforeEach((to, from, next) => {
  console.log(to);
  console.log('123');
  console.log(from);
  next();
})
window.router = router;
